# encoding=utf-8

# ---------------------------------------------------------------------------------------------------------
#
#  发布脚本
#
# ---------------------------------------------------------------------------------------------------------

import logging
import os
import shutil

import config


class Handler(object):
    '''文档发布
    '''

    def __init__(self, base_path, is_reference, markdowns, deleted) -> None:
        super().__init__()

        # 发布路径
        self._deploy_path = config.DEPLOY_PATH
        # 工作路径
        self._markdown_path = base_path + 'markdown/'
        # 是否引用文档目录
        self._is_reference = is_reference

        # 需要发布的 markdown
        self._markdowns = markdowns
        # 删除的文档ID
        self._deleted = deleted

    def _deploy(self, markdown):
        '''发布单个文档
        '''
        file_path = self._get_deploy_path() + markdown.document_id
        # 删除旧文档
        if os.path.exists(file_path):
            logging.debug('清理旧文档 %s', file_path)
            shutil.rmtree(file_path)

        # 发布新文档
        logging.debug('复制新文档 %s', markdown.context_path())
        shutil.copytree(markdown.context_path(), file_path)

        pass

    def _update_main_table(self):
        '''更新主目录及主页面列表
        '''
        sider_bar_path_source = self._markdown_path + config.SIDEBAR_NAME
        home_page_path_source = self._markdown_path + config.HOME_PAGE_NAME

        sider_bar_path_target = self._get_deploy_path() + config.SIDEBAR_NAME
        home_page_path_target = self._get_deploy_path() + config.HOME_PAGE_NAME

        logging.info('更新主目录 %s', sider_bar_path_target)
        shutil.copyfile(sider_bar_path_source, sider_bar_path_target)

        logging.info('更新主页面列表 %s', home_page_path_target)
        shutil.copyfile(home_page_path_source, home_page_path_target)

    def _get_deploy_path(self):
        '''处理发布路径
        '''
        if self._is_reference:
            return self._deploy_path + config.REFERENCE_LINK_PREFIX
        return self._deploy_path

    def handle(self):
        '''发布文档
        '''

        print('-------------------------------------------------------------------------------------------------------')
        logging.info('发布文档开始 %s', self._markdown_path)

        # 部署变更的文档
        logging.info('部署文档(%s) %s', len(self._markdowns), self._get_deploy_path())
        for md in self._markdowns:
            self._deploy(md)

        # 删除已移除的文档
        logging.info('清理已删除文档(%s) %s', len(self._deleted), self._deleted)

        for document_id in self._deleted:
            # 删除部署路径的文档
            document_path = self._get_deploy_path() + document_id
            logging.debug('删除已发布文档 %s', document_path)
            shutil.rmtree(document_path)

            # 删除工作路径的 markdown
            markdown_path = self._markdown_path + document_id
            logging.debug('删除临时文档 %s', markdown_path)
            shutil.rmtree(markdown_path)

        # 更新主目录
        self._update_main_table()
        logging.info('发布文档完成')
